// Implementation of the ServerSocket class

#include "ServerSocket.h"
#include "SocketException.h"
#include <string>
#include <sstream>
#include <cstdio>

using namespace std;


ServerSocket::ServerSocket ( int port )
{
  if ( ! Socket::create() )
    {
      throw SocketException ( "Could not create server socket." );
    }

  if ( ! Socket::bind ( port ) )
    {
      throw SocketException ( "Could not bind to port." );
    }

  if ( ! Socket::listen() )
    {
      throw SocketException ( "Could not listen to socket." );
    }

}

ServerSocket::~ServerSocket()
{
}

string itostr(int n)
{
    stringstream ss;
    ss<<n;
    return ss.str();
}

int strtoi(string s)
{
    int i;
    sscanf(s.c_str(), "%d", &i);
    return i;
}

const ServerSocket& ServerSocket::operator << ( const std::string& s ) const
{
  if ( ! Socket::send ( s ) )
    {
      throw SocketException ( "Could not write to socket." );
    }

  return *this;

}

const ServerSocket& ServerSocket::operator << ( const int& n ) const
{
  if ( ! Socket::send ( itostr(n) ) )
    {
      throw SocketException ( "Could not write to socket." );
    }

  return *this;

}


const ServerSocket& ServerSocket::operator >> ( std::string& s ) const
{
  if ( ! Socket::recv ( s ) )
    {
      throw SocketException ( "Could not read from socket." );
    }

  return *this;
}

const ServerSocket& ServerSocket::operator >> ( int& n ) const
{
    string s;
  if ( ! Socket::recv ( s ) )
    {
      throw SocketException ( "Could not read from socket." );
    }
   n=strtoi(s);

  return *this;
}

void ServerSocket::accept ( ServerSocket& sock )
{
  if ( ! Socket::accept ( sock ) )
    {
      throw SocketException ( "Could not accept socket." );
    }
}
